package com.csyf.manager.service.impl;

import com.csyf.manager.common.CommonConst;
import com.csyf.manager.dao.SysAgentDao;
import com.csyf.manager.dao.SysAgentMerchantMapper;
import com.csyf.manager.entity.SysAgent;
import com.csyf.manager.entity.SysAgentMerchant;
import com.csyf.manager.entity.SysMerchant;
import com.csyf.manager.entity.SysUser;
import com.csyf.manager.exception.ApiValidateException;
import com.csyf.manager.service.SysAgentService;
import com.csyf.manager.service.SysUserService;
import com.csyf.manager.utils.page.JqGridVo;
import com.csyf.manager.utils.page.PageUtils;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @Author: casper
 * @Description: 代理商ServiceImpl
 * @Date: Created in 2019/3/20 17:05
 */
@Slf4j
@Service
public class SysAgentServiceImpl implements SysAgentService {

    @Autowired
    private SysAgentDao sysAgentDao;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysAgentMerchantMapper sysAgentMerchantMapper;

    @Override
    public JqGridVo querydata(SysAgent vo, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("id desc");

        Example example = new Example(SysAgent.class);
        Example.Criteria criteria = example.createCriteria();
        PageUtils.andLikeTo(criteria, "agentName", "%" + vo.getAgentName() + "%");
        PageUtils.andEqualTo(criteria, "agentPhone", vo.getAgentPhone());
        PageUtils.andEqualTo(criteria, "agentNo", vo.getAgentNo());

        List<SysAgent> select = sysAgentDao.selectByExample(example);
        return PageUtils.pasrJqGrid(select);
    }

    @Transactional
    @Override
    public void saveAgent(SysAgent agentForm) throws ApiValidateException {

        SysAgent sysAgent = new SysAgent();
        sysAgent.setAgentPhone(agentForm.getAgentPhone());
        int i = sysAgentDao.selectCount(sysAgent);
        if (i > 0) {
            throw new ApiValidateException("手机号重复");
        }
        sysAgent = new SysAgent();
        sysAgent.setAgentAccount(agentForm.getAgentAccount());
        i = sysAgentDao.selectCount(sysAgent);
        if (i > 0) {
            throw new ApiValidateException("账号重复");
        }

        //添加代理商用户
        SysUser user = new SysUser();
        user.setUserName(agentForm.getAgentAccount());
        user.setPassword(agentForm.getAgentPwd());
        user.setCreateTime(new Date());
        user.setEmail("");
        user.setMobile(agentForm.getAgentPhone());
        user.setStatus(CommonConst.STATUS_VALID.toString());
        user.setUserType(CommonConst.AGENT_USER);
        user.setDescription("代理商用户");
        sysUserService.addUserAndGetId(user);

        //分配商户角色
        sysUserService.addAssignRole(user.getUserId(), Arrays.asList("2"));


        agentForm.setAgentStatus(1);
        agentForm.setCreateTime(new Date());
        agentForm.setModifyTime(new Date());
        sysAgentDao.insertSelective(agentForm);

        int i1 = new Random().nextInt(10);

        agentForm.setUserId(Long.valueOf(user.getUserId()));
        agentForm.setAgentStatus(1);
        String mer = "DL";
        agentForm.setAgentNo(mer + (agentForm.getId() * 10 + i1));
        //agentForm.setAgentSignkey(DigestUtils.md5Hex(vo.getMerchMerchantNo() + RandomStringUtils.random(4, "abcdefgABCDEFG123456789")));
        sysAgentDao.updateByPrimaryKey(agentForm);
    }

    /**
     * 根据ID查询代理商
     * @param agentId
     * @return
     */
    @Override
    public SysAgent queryAgentById(Long agentId) {
        return sysAgentDao.selectByPrimaryKey(agentId);
    }

    @Override
    public int updateByAgentId(SysAgent agentForm) {
        agentForm.setModifyTime(new Date());
        return sysAgentDao.updateByAgentId(agentForm);
    }

    /**
     * 根据代理商id集合批量更新代理商状态
     * @param agentIds
     * @param status
     * @return
     */
    @Override
    public int updateStatusBatch(List<String> agentIds, Integer status) {
        Map<String,Object> params = new HashMap<>(2);
        params.put("agentIds", agentIds);
        params.put("agentStatus", status);
        return sysAgentDao.updateStatusBatch(params);
    }

    /**
     * 根据代理商Id分配商户
     * @param agentId
     * @param merchIdsList
     */
    @Override
    public void addAssignMerch(Long agentId, List<String> merchIdsList) {
        try {
            SysAgentMerchant agentMerchant = new SysAgentMerchant();
            agentMerchant.setAgentId(agentId);
            sysAgentMerchantMapper.delete(agentMerchant);
            for (String merchId : merchIdsList) {
                agentMerchant.setMerchId(Long.valueOf(merchId));
                sysAgentMerchantMapper.insert(agentMerchant);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据用户id查询代理商信息
     * @param userId
     * @return
     */
    @Override
    public SysAgent queryAgentByUserId(Long userId) {
        SysAgent agent = new SysAgent();
        agent.setUserId(userId);
        SysAgent selectOne = sysAgentDao.selectOne(agent);
        return selectOne;
    }
}
